import { taskType } from "../../enum";
import { spawnCreepByTask } from "../../tools/tools/spawnTool";
import structureTool from "../../tools/tools/structureTool";
import eventManager from "../event/eventManager";
import { eventMap } from "../event/eventMap";
import taskManager, { pushNeedResourceTask } from "../task/taskManager";

function _mountSpawn() {
    Object.assign(Spawn.prototype, extension)
}

const extension = {
    taskPool: [taskType.spawnCreep],
    /**TODO:所有建筑物的初始化 */
    init: function (params = {}) {
        const { taskPool = [taskType.spawnCreep] } = params
        this.taskPool = taskPool
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        objMemory['state'] = {}
        objMemory['state']['needEnergy'] = { isNeed: false }
        this.updateSelfState()
    },
    /**自检并执行任务*/
    run: function () {
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        if (!objMemory.isRuning) {
            // 非运行中，可执行任务
            let isRuning = false
            let getTaskResult = this.getTask()          // 只获取任务id
            // console.log('spawn的任务执行情况');
            let taskDeta = getTaskResult['taskDeta']
            let taskID = getTaskResult['taskID']
            if (taskID) {
                switch (getTaskResult['taskType']) {
                    case taskType.spawnCreep:      // 生产creep的任务
                        isRuning = spawnCreepByTask(this, taskID, taskDeta)
                        break;
                    default:
                        break;
                }
            }
            if (objMemory.publishTask.length == 0) {
                // 未发布任务
                this.updateSelfState()
                if (objMemory['state']['needEnergy'].isNeed) pushNeedResourceTask(this, { [RESOURCE_ENERGY]: this.store.getFreeCapacity(RESOURCE_ENERGY) })
            }
            if (!isRuning) {
                // 无任务，则进入休眠状态，一段时间后自动唤醒
                objMemory.isRuning = true
                eventManager.add(`无任务或当前能量不足，${this.name}进入休眠,等待唤醒`, 30, eventMap.objToSleep, { objID: this.id })
            }
        }
    },
    /**检查自身状态，避免出现异常数据 */
    checkSelf: function () {
        let isRuning = false
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        // 避免isRuning进入死循环:
        if (this.spawning) isRuning = true   // 不是处于spawing状态
        if (Object.keys(Memory.event).map(eventID => {
            let eventDeta = Memory.event[eventID]
            if (eventDeta['eventMap'] == eventMap.objToSleep.name && eventDeta['params']['objID'] == this.id) {
                isRuning = true
            } else {
                isRuning = isRuning || false
            }
        }))
            objMemory.isRuning = isRuning
        // 避免publishTask出现异常
        if (objMemory.publishTask.length != 0) {
            let publishTaskList = []
            objMemory.publishTask.map(taskID => { if (Memory.rooms[this.pos.roomName]['task']['taskDeta'][taskID]) publishTaskList.push(taskID) })
            objMemory.publishTask = publishTaskList   // 更新发布的任务
        }
        //能量满足，则清除当前挂载的needResource任务。ps：20240125好像会导致carrier的逻辑出现问题
        // this.updateSelfState()
        // if (!objMemory['state']['needEnergy']) {
        //     objMemory.publishTask.map(taskID => {
        //         let taskDeta = taskManager.getTaskByID(taskID, this.id, this.pos.roomName, false)
        //         if (taskDeta.taskType == taskType.needResource) {
        //             if (taskDeta.doing) return  //已经被领取的任务则跳过
        //             taskManager.finishTask(taskID, this.pos.roomName)
        //         }
        //     })
        // }
    },
    /**更新自身状态 */
    updateSelfState: function () {
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        objMemory['state']['needEnergy'] = structureTool.isNeedEnergy(this, { resource: RESOURCE_ENERGY, limit: 1 })
    },

    /**根据任务池获取任务 */
    getTask: function () {
        let result = { 'taskID': null, 'taskType': null }
        this.taskPool.map(taskType => {
            if (result['taskID']) return
            result = taskManager.getTaskByType(taskType, this.id, this.pos.roomName)
            result['taskType'] = taskType
        })
        return result
    },
    /**自检并推送任务 */
    pushTask: function () {

    },
}


export default _mountSpawn